import axios from 'axios'
import { Message } from 'element-ui'
import router from '@/router'
import {
  showLoading,
  hideLoading
} from './loading'
import store from '@/store'
var baseurl = window.location.origin
if (process.env.NODE_ENV === 'development') {
  // baseurl = window.location.origin + '/api' // dev
  baseurl = window.location.origin + '/obportal/api' // 外网test
} else if (process.env.NODE_ENV === 'production') {
  // baseurl = window.location.origin + '/dev/api' // dev
  // baseurl = window.location.origin + '/test/api' // test
}
function publicParam () {
  const param = {}
  const newTime = new Date().format('yyyyMMddhhmmss')
  param.version = '1.0.0'
  param.orderId = newTime + Math.floor(Math.random() * 10) + Math.floor(Math.random() * 10) + Math.floor(Math.random() * 10) + Math.floor(Math.random() * 10)
  param.txnTime = newTime
  param.channelCode = 'PO01'
  param.attach = {}
  return param
}
const instance = axios.create({
  baseURL: baseurl,
  withCredentials: true,
  timeout: 60000,
  method: 'post',
  headers: { 'Content-Type': 'application/json;charset=UTF-8' }
})

instance.interceptors.request.use(config => {
  if (!config.data) config.data = {}
  var params = publicParam()
  config.data.sessionId = localStorage.getItem('sessionId') || ''
  params.reqData = config.data
  config.data = params
  if (config.showLoading) {
    showLoading()
  }
  return config
})
instance.interceptors.response.use(
  response => {
    const res = response.data || {}
    if (['999'].indexOf(res.respCode) !== -1) {
      if (res.respMsg) {
        // Message.error(res.respMsg)
      }
      store.commit('updateToken')
      router.push('/login')
    }
    if (response.config.showLoading) {
      hideLoading()
    }
    return res
  },
  error => {
    if (error.config.showLoading) {
      hideLoading()
    }
    Message.error(error.message)
    return Promise.reject(error)
  }
)
export default instance
